import {getUrlFor} from "@/services/UrlConfig";
import axios from 'axios';
import {encSha512} from "@/services/encrypto";
import React from "react";
import {formatResult} from "@/services/Utils";
import Cookies from 'js-cookie'

async function AdminLogin(params: Domain.AdminSignInParams) {
  // @ts-ignore
  let user = Cookies.get("currentAdmin");
  if (user){
    return {
      data: JSON.parse(user),
      status: 200
    };
  }
  if (params.account && params.password){
    const msg = await axios.get(getUrlFor("/admin/"+params.account, {
      password: encSha512(params.password)
    }));
    if (msg.status === 200) {
      Cookies.set("currentAdmin", JSON.stringify(msg.data));
      return msg;
    }
    else return Promise.reject("请求错误");
  }

  return Promise.reject("账号密码未填");
}

async function addAdmin(info: Domain.Admin) {
  /*验证号的各个参数的完备性*/
  if (info.password)
    info.password=encSha512(info.password)
  await axios.post(getUrlFor("/admin", info), info)
}

const rmAdmin = async (account: string|undefined) => {
  await axios.delete(getUrlFor("/admin/"+account));
}

async function fetchAllAdmin(params: API.PageParams,
                             sort: Record<string, 'ascend'|'descend'|null>,
                             filter: Record<string, React.ReactText[]|null>) {
  const reqParams = {
    start: params.current,
    size: params.pageSize
  }
  console.log(sort, filter);
  const res = await axios.get(getUrlFor("/admin", reqParams))
  return formatResult(res);
}

const updateAdmin = async (info: Domain.Admin) => {
  await axios.put(getUrlFor("/admin/"+info.account), info);
}

const outLogin = async () => {
  Cookies.set("currentAdmin", "");
}


export {AdminLogin, addAdmin, fetchAllAdmin, rmAdmin, updateAdmin, outLogin}
